package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx-learn/ziface"
)

type ConnManager struct {
	connections map[uint32]ziface.IConnection // 管理的连接信息
	connLock    sync.RWMutex                  // 读写连接的读写锁
}

func (c *ConnManager) Add(conn ziface.IConnection) {
	// 保护共享资源 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()
	connectionID := conn.GetConnectionID()
	c.connections[connectionID] = conn
	fmt.Println("add connection success connectionID = ", connectionID)
}

func (c *ConnManager) Remove(conn ziface.IConnection) {
	c.connLock.Lock()
	defer c.connLock.Unlock()
	connectionID := conn.GetConnectionID()
	delete(c.connections, connectionID)
	fmt.Println("remove conn success connectionID = ", connectionID)
}

func (c *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	c.connLock.RLock()
	defer c.connLock.RUnlock()
	connection, ok := c.connections[connID]
	if ok {
		return connection, nil
	}
	return nil, errors.New(fmt.Sprintf("not found Conn connID= %d \n", connID))
}

func (c *ConnManager) Len() int {
	return len(c.connections)
}

func (c *ConnManager) ClearConn() {
	for connID, conn := range c.connections {
		conn.Stop()
		delete(c.connections, connID)
	}
	fmt.Println("clear all connection !")
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}
